package com.scfire.donate

import grails.converters.JSON

import java.text.SimpleDateFormat

import net.sf.json.JSONArray
import net.sf.json.JSONObject

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.scfire.baseInfo.Gson
import com.scfire.fund.FDonate
import com.scfire.fund.FRuler
import com.scfire.project.*
import com.scfire.security.Member
import com.scfire.weixin.WeiXinConstants

class DonateController {
	
	
	def Log LOG = LogFactory.getLog(DonateController.class)
	
	def springSecurityService
	def deviceInfoService
	def weiXinService
	def mongo
	
	/**
	 * 项目捐赠列表信息
	 * @param project
	 * @return null
	 *
	 * **/
    /*def donateList() {		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		params.max=20
		String projectId = params.projectId
		if(projectId == null){
			notFound()
			return
		}
		
		Project project = Project.findById(projectId)
		if(project == null){
			notFound()
			return
		}
		def subdonateCount = 0;
		def subLoveCount=0
		//def donates = project.donates;
		def subDonatesSort = project.subProjects
		if(subDonatesSort!=null){
			subLoveCount=subDonatesSort.size()
			for(SubProject sb :subDonatesSort){
				if(sb?.donates){
					subdonateCount+=sb?.donates.size()
				}
			}
		}
		
		
		def Criteria = Donate.createCriteria()
		def fc = {
			eq("project",project)
			order("date","desc")
		}
		
		def donatesSub = Criteria.list(params,fc)
		def donateCount = donatesSub.size()
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "donatelistmb", model: [donates:donatesSub, user:user,roles:roles,donateCount:donateCount, subDonates:subDonatesSort, subdonateCount:subdonateCount,subLoveCount:subLoveCount]
				}
				if("mobile".equals(str)){
					render view: "donatelistmb", model: [donates:donatesSub, user:user,roles:roles,donateCount:donateCount, subDonates:subDonatesSort, subdonateCount:subdonateCount,subLoveCount:subLoveCount]
				}
			}
			json {
				JSONArray donatesjson = new JSONArray()
				for(Donate donate:donatesSub){
					JSONObject json = new JSONObject()
					json.put("headimgurl",donate.member.headimgurl)
					json.put("nickname", donate.member.nickname)
					json.put("donate_fee", donate.donate_fee)
					json.put("money",donate.money)
					if(donate?.fDonate?.donate_fee){
						json.put("fDonatemoney",(donate?.fDonate?.donate_fee)/100)
					}else{
					json.put("fDonatemoney",0)
					}
					json.put("date",sdf.format(donate.date).substring(5))
					//(donate.date.getMonth()+1)+"-"+donate.date.getDate()+" "+donate.date.getHours()+":"+donate.date.getMinutes()
				    json.put("text", donate.comment?.text)
					donatesjson.add(json)
				}
				render donatesjson as JSON
			}
		}
		
	}*/
	
	/**
	 * 项目捐赠列表信息
	 * @param project
	 * @return null
	 *
	 * **/
	def donateList() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		params.max=20
		String projectId = params.projectId
		if(projectId == null){
			notFound()
			return
		}
		Project project = Project.findById(projectId)
		if(project == null){
			notFound()
			return
		}
		def subdonateCount = 0;
		def subLoveCount=0
		//def donates = project.donates;
		//def subDonatesSort = project.subProjects
		/*long l=new Date().getTime()
		if(subDonatesSort!=null){
			subLoveCount=project.sbuProjectSize
			for(SubProject sb :subDonatesSort){
				if(sb?.donates){
					subdonateCount+=sb?.donates.size()
				}
			}
		}
		println (new Date().getTime()-l)*/
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "donatelistmb", model: [ user:user,roles:roles,project:project]
				}
				if("mobile".equals(str)){
					render view: "donatelistmb", model: [ user:user,roles:roles,project:project]
				}
			}
		}
		
	}
	
	/**
	 * 项目捐赠列表信息
	 * @param project
	 * @return null
	 *
	 * **/
	def donateList2() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		params.max=20
		String projectId = params.projectId
		if(projectId == null){
			notFound()
			return
		}
		Project project = Project.findById(projectId)
		if(project == null){
			notFound()
			return
		}
		def Criteria = Donate.createCriteria()
		def fc = {
			eq("project",project.id)
			order("date","desc")
		}
		def donatesSub = Criteria.list(params,fc)
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
		withFormat {
			json {
				JSONArray donatesjson = new JSONArray()
				for(Donate donate:donatesSub){
					JSONObject json = new JSONObject()
					def member2 = Member.findById(donate.member)
					json.put("headimgurl",member2?.headimgurl)
					json.put("nickname", member2?.nickname)
					json.put("id", member2.id)
					json.put("donate_fee", donate.donate_fee)
					json.put("money",donate.money)
					def fdonate = FDonate.findByDonate(donate.id)
					if(fdonate){
						json.put("fDonatemoney",(fdonate.donate_fee)/100)
					}else{
					json.put("fDonatemoney",0)
					}
					json.put("date",sdf.format(donate.date).substring(5))
					//(donate.date.getMonth()+1)+"-"+donate.date.getDate()+" "+donate.date.getHours()+":"+donate.date.getMinutes()
					def comment = Comment.findByDonate(donate.id)
					if(comment){
						if(false!=comment?.display_flag){
							json.put("text",comment?.text)
						}
					}else{
						json.put("text", "")
					}
					
					donatesjson.add(json)
				}
				render donatesjson as JSON
			}
		}
		
	}
	
	/*def subDonateList(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		params.max = 20
		String projectId = params.projectId
		if(projectId == null){
			notFound()
			return
		}
		
		Project project = Project.findById(projectId)
		if(project == null){
			notFound()
			return
		}
		List<SubProject> subDonatesSort = new ArrayList<SubProject>();
		def SCriteria = SubProject.createCriteria()
		def fcd={
			eq("project", project.id)
			order("subdonate","desc")
		}
		
		def subDonates = SCriteria.list(params, fcd);
		println (subDonates.size()+"------------")
		for(def subd: subDonates){
			subDonatesSort.add(subd);
		}
//		
//		Collections.sort(subDonatesSort);
		
		withFormat {
			html {
				if("pc".equals(str)){
					render "待开发"
				}
				if("mobile".equals(str)){
					render "待开发"
				}
			}
			json {
				JSONArray subprojectsjson = new JSONArray()
				for(SubProject sproject:subDonatesSort){
					def donates =sproject.donates
					int donate_fee=0
					for(Donate d:donates){
						if(d?.fDonate?.donate_fee){
							donate_fee+=d?.fDonate?.donate_fee
						}
						
					}
					JSONObject json = new JSONObject()
					json.put("id",sproject.id)
					json.put("headimgurl",sproject.member.headimgurl)
					json.put("nickname", sproject.member.nickname)
					json.put("subdonateSize", sproject.donates.size())
					json.put("subdonate",sproject.subdonate)
					json.put("donate_fee",donate_fee/100)
					
					json.put("description", sproject.subdescription)
					subprojectsjson.add(json)
				}
				render subprojectsjson as JSON
			}
		}
		
	}*/
	
	def subDonateList(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		params.max = 20
		String projectId = params.projectId
		if(projectId == null){
			notFound()
			return
		}
		Project project = Project.findById(projectId)
		if(project == null){
			notFound()
			return
		}
		List<SubProject> subDonatesSort = new ArrayList<SubProject>();
		def SCriteria = SubProject.createCriteria()
		def fcd={
			eq("project", project.id)
			order("subdonate","desc")
		}
		def subDonates = SCriteria.list(params, fcd);
		for(def subd: subDonates){
			subDonatesSort.add(subd);
		}
//		Collections.sort(subDonatesSort);
		
		withFormat {
			json {
				JSONArray subprojectsjson = new JSONArray()
				for(SubProject sproject:subDonatesSort){
					def member2 = Member.findById(sproject.member)
					JSONObject json = new JSONObject()
					json.put("id",sproject.id)
					json.put("headimgurl",member2?.headimgurl)
					json.put("nickname", member2?.nickname)
					json.put("subdonateSize", sproject.subdonateSize)
					json.put("subdonate",sproject.subdonate)
					json.put("donate_fee",sproject.subfdonate/100)
					json.put("description", sproject.subdescription)
					subprojectsjson.add(json)
				}
				render subprojectsjson as JSON
			}
		}
		
	}
	
	
	def donateThanks(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String subid = params.subprojectId;
		
		int subProjectSize = Donate.countBySubProject(Integer.parseInt(subid));
		render view:"donate_list_thanks", model:[subProjectSize:subProjectSize,subprojectId:subid]
	}
	
	
	def donateThanks2(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		params.max = 20
		String subid = params.subprojectId;
		def subProject = SubProject.findById(Integer.parseInt(subid));
		def Criteria = Donate.createCriteria()
		def fc = {
			eq("subProject",subProject.id)
			order("date","desc")
		}
		def donatesSub = Criteria.list(params,fc)
		def fRuler= FRuler.findByProject(subProject?.project)
		
		withFormat {
			json {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
				JSONArray donatesjson = new JSONArray()
				for(Donate donate:donatesSub){
					JSONObject json = new JSONObject()
					def member2 = Member.findById(donate.member)
					json.put("headimgurl",member2.headimgurl)
					json.put("nickname", member2?.nickname)
					json.put("id", member2.id)
					json.put("donate_fee", donate.donate_fee)
					json.put("money",donate.money)
					if(donate?.fDonate?.donate_fee){
						json.put("fDonatemoney",(donate?.fDonate?.donate_fee)/100)
					}else{
					json.put("fDonatemoney",0)
					}
					json.put("date",sdf.format(donate.date).substring(5))
					//(donate.date.getMonth()+1)+"-"+donate.date.getDate()+" "+donate.date.getHours()+":"+donate.date.getMinutes()
					def comment= Comment.findById(donate.comment)
					if(comment){
						json.put("text", comment?.text)
					}else{
						json.put("text", "")
					}
					
					donatesjson.add(json)
				}
				render donatesjson as JSON
			}
		}
	}
	
	
	
	/**
	 * 项目捐赠用户详情
	 * @param user
	 * @return null
	 *
	 * **/
	def donateDetail() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "donatedetailmb", model: [user:user,roles:roles]
				}
				if("mobile".equals(str)){
					render view: "donatedetailmb", model: [user:user,roles:roles]
				}
			}
			json {
				
			}
		}
		
	}
	
	/**
	 * 捐赠操作
	 * @param user
	 * @return null
	 *
	 * **/
	def donate() {
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "donatedetailmb", model: [user:user,roles:roles]
				}
				if("mobile".equals(str)){
					render view: "donatedetailmb", model: [user:user,roles:roles]
				}
			}
			json {
				
			}
		}
		
	}
	
	
	
	/**
	 * 保存捐赠留言
	 * @param Donate id
	 * @return null
	 *
	 * **/
	def savedonateInfo(Comment comment){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String donateid = params.donateid
		Donate donate = null
		Member member = (Member)user
		
		try{
			
			def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
			DBCollection projectCollection = db.getCollection("donate")
			DBObject queryCondition= new BasicDBObject()
			queryCondition.put("_id",Integer.valueOf(donateid))
			
			
			
			comment.member = member.id
			donate = Donate.findById(Long.valueOf(donateid))
			comment.donate = donate.id
			comment.createDate = new Date();
			comment.save(flush:true)
			if(!comment.save()){
				comment.errors.allErrors.each{
					println(it)
				}
			}
			/*donate.comment = comment
			donate.save(flush:true)*/
			BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("comment", comment.id))
			
			projectCollection.update(queryCondition, updateParameter,true,true)
			
			
		}catch(Exception e){
			LOG.error("save donate comment Info catche exception."+e.getMessage())
		}
		
		//现在跳回原电子证书页面
		redirect (action: "donateElectronicInfo", params:[donateid: donateid])
	}
	
	
	/**
	 * 捐赠电子证书
	 * @param Donate id
	 * @return null
	 *
	 * **/
	def donateElectronicInfo(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		String donateid = params.donateid
		
		//微信分享参数
		def url = WeiXinConstants.server + "/donate/donateElectronicInfo?"+request.getQueryString()
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.server+"/images/heart.png"
		Donate donate = null
		Member member = null
		Project project = null
		def shareUrl = "##";
		def fRuler
		Comment commentInstance = new Comment();
		def comment
		try{
			donate = Donate.findById(Long.valueOf(donateid))
			member = Member.findById(donate?.member) 
			project =Project.findById(donate?.project)
			if(donate?.project){
				fRuler = FRuler.findByProject(project)
			}
			 comment =  Comment.findByDonate(donate.id)
			 println "-------"+comment?.text+"---------"
			shareUrl = WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id
		}catch(Exception e){
			LOG.error("get donate Electronic Info catch exception."+e.getMessage()+ "donateid:"+donateid)
		}
		render view: "donateelectronicinfomb", model: [text:comment?.text,fRuler:fRuler,user:(Member)user, comment:commentInstance, donate:donate,member:member,project:project,   appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,url:url , imgUrl : imgUrl , shareUrl:shareUrl ]
	}
	
	/**
	 * 捐赠电子证书 ----静态页面
	 * @param Donate id
	 * @return null
	 *
	 * **/
	def donateElectronicInfo2(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		
		//判断捐赠记录是否已保存到数据库中
		String donateNoNew = params.donateNoNew
		if(donateNoNew){
			Donate donate = Donate.findByDonateNoNew(donateNoNew)
			if(donate){
				redirect(controller: "donate" , action: "donateElectronicInfo", params: [donateid: donate?.id])
				return
			}
		}
		
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def donate_fee = params.donate_fee
		def projectid = params.projectid
		def fRuler
		
		//微信分享参数
		def url = WeiXinConstants.server + "/donate/donateElectronicInfo2?"+request.getQueryString()
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.server+"/images/heart.png"
		
		Donate donate = null
		Project project = null
		def shareUrl = "##";
		float fdonatemoney=0
		float donate_feeFloat
		try{
			project = Project.findById(projectid)
			if(project!=null){
				if(donate_fee instanceof  Float){
					donate_feeFloat=donate_fee
				}else if (donate_fee instanceof  Integer){
				donate_feeFloat=(float)donate_fee
				}else{
				donate_feeFloat=Float.parseFloat(donate_fee)
				}
				
				fRuler = FRuler.findByProjectAndStatus(project,"true")
				if(fRuler != null){
				int donatemoney = donate_feeFloat*100
				int bandfund = fRuler.bandfund
				int donatefund = fRuler.donatefund
				String regular = fRuler.regular
				float regularAvg
				int regularUser =1
				int regularPool=1
				String[] aa = regular.split(":");
				int a =aa.length;			
				regularAvg=Float.parseFloat(aa[1])/Float.parseFloat(aa[0])
				
				//计算可用金额 = 绑定配捐金额-实际已配捐金额
				int restfund = bandfund - donatefund			
				if(restfund > 0){
					//可用金额根据配捐规则大于此次要配捐的金额,则进行配捐
					if(restfund >= donatemoney*regularAvg){
						fdonatemoney = donatemoney*regularAvg/100
						
					}else{
						//最后剩余的全部进行配捐
						fdonatemoney = restfund/100
					}
				}	
			}
				
			}
			shareUrl = WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id
		}catch(Exception e){
			LOG.error("get donate Electronic Info2 catch exception."+e.getMessage())
		}
		
		render view: "donateelectronicinfomb2", model: [fRuler:fRuler,fdonatemoney:fdonatemoney,member : user, project:project, donate_fee:donate_fee,  appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,url:url , imgUrl : imgUrl , shareUrl:shareUrl ]
	}
	
	/*
	* 用户信息未找到
	* @param null
	* @return null
	*
	* **/
   protected void notFound() {
	   def gson = new Gson()
	   withFormat {
		   html {
			   flash.message = "未找到项目！"
			   redirect (controller: "errors", action: "notFound")
		   }
		   json {
			   gson.setResult(false)
			   gson.setCode(404)
			   gson.setInfo(["text": "未找到项目！"])
			   render gson as JSON
		   }
	   }
   }
	
}
